package com.lxd.aspect;

import com.lxd.annotaion.GlobalInterceptor;
import com.lxd.entity.TokenUserInfoDto;
import com.lxd.entity.enums.ResponseCodeEnum;
import com.lxd.exception.BusinessException;
import com.lxd.redis.RedisComponent;
import com.lxd.redis.RedisUtil;
import com.lxd.utils.StringTools;
import com.mysql.cj.log.Log;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;


/**
 * @Author Dongdong
 * @注释  全局拦截异常
 */
@Aspect
@Component
public class GlobalOperationAspect {
    private Logger logger = LoggerFactory.getLogger(GlobalOperationAspect.class);
    @Autowired
    private RedisUtil redis;
    @Autowired
    private RedisComponent redisComponent;

    public void checkGlobalInterceptor() {
    }

    @Pointcut("@annotation(com.lxd.annotaion.GlobalInterceptor)")
    private void pointcut() {
    }

    @Before(value = "pointcut()")
    public void interceptor(JoinPoint joinPoint) {
        try {
            Method methods = ((MethodSignature) joinPoint.getSignature()).getMethod();
            GlobalInterceptor annotation = methods.getAnnotation(GlobalInterceptor.class);
            if (annotation == null) {
                return;
            }
            if (annotation.checkLogin() || annotation.checkAdmin()) {
                checkLogin(annotation.checkAdmin());
            }
        } catch (BusinessException e) {
            logger.error("全局拦截异常", e);
        } catch (Exception e) {
            logger.error("全局拦截异常", e);
        } catch (Throwable e) {
            logger.error("全局拦截异常", e);
        }

    }

    public void checkLogin(boolean checkAdmin) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("Token");
        if (StringTools.isEmpty(token)) {
            throw new BusinessException(ResponseCodeEnum.CODE_901);
        }
        //从redis中获取token体，如果存在，说明登录，不存在说明没登录
        TokenUserInfoDto tokenUserInfoDto = redisComponent.getTokenUserInfoDto(token);
        //从token体中获取admin 信息，验证是否是管理员
        Boolean isAdmin = tokenUserInfoDto.getAdmin();
        //该接口 需要校验 && 请求该接口的人不是管理员
        if (checkAdmin && !isAdmin) {
            throw new BusinessException(ResponseCodeEnum.CODE_404);
        }
    }
}
